﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CrazyWorship1.ListenerService;
using System.Windows.Markup;
using System.Xml;
using System.ComponentModel;

namespace CrazyWorship1
{
    /// <summary>
    /// Interaction logic for LyricController.xaml
    /// </summary>
    public partial class LyricController : UserControl
    {
        Dictionary<string, UIElement> Lyrics = new Dictionary<string, UIElement>();
        Song _song;
        ClientManager _clientManager;
        public LyricController()
        {
            InitializeComponent();
            _itemsControl.ItemsSource = Lyrics;
        }
        #region LyricControlNameProperty
        public static readonly DependencyProperty LyricControlNameProperty =
            DependencyProperty.Register("LyricControlName", typeof(string),
            typeof(LyricController),
            new PropertyMetadata(OnLyricControlNameChanged));

        public string LyricControlName
        {
            get
            {
                object result = GetValue(LyricControlNameProperty);
                return (string)result;
            }
            set
            {
                SetValue(LyricControlNameProperty, value);
            }
        }
        static private void OnLyricControlNameChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {

        }



        #endregion



        #region AutostartProperty
        public static readonly DependencyProperty AutoStartProperty =
            DependencyProperty.Register("AutoStart", typeof(bool),
            typeof(LyricController),
            new PropertyMetadata(OnAutoStartChanged));

        public bool AutoStart
        {
            get
            {
                object result = GetValue(AutoStartProperty);
                return (bool)result;
            }
            set
            {
                SetValue(AutoStartProperty, value);
            }
        }
        static private void OnAutoStartChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            if ((bool)e.NewValue)
                ((LyricController)obj).startButton.Visibility = Visibility.Hidden;
            else
                ((LyricController)obj).startButton.Visibility = Visibility.Visible;
        }



        #endregion



        private void button4_Click(object sender, RoutedEventArgs e)
        { StartSong(); }

        private void button5_Click(object sender, RoutedEventArgs e)
        { EndSong(); }

        public void StartSong()
        { SongOverride(true); }

        public void EndSong()
        { SongOverride(false); }

        public void SongOverride(bool active)
        {
            foreach (BaseListenerClient s in ClientManager.ConnectedClients)
                s.SongOverride(active);
        }
        public void SetNextSlide(string i)
        {
            foreach (BaseListenerClient s in ClientManager.ConnectedClients)
                s.SendDataString(this.LyricControlName, i);
        }

        public ClientManager ClientManager
        {
            get
            { return _clientManager; }
            set
            {
                _clientManager = value;
                this.DataContext = this;
            }
        }
        public Song Song
        {
            get
            { return _song; }
            set
            {
                _song = value;
                UpdateLyrics();
            }
        }
        private void EFSelectedIndexChanged(object sender, EventArgs e)
        {
            int sel = ((sender as FluidKit.Controls.ElementFlow).SelectedIndex);
            KeyValuePair<string, UIElement> a = (KeyValuePair<string, UIElement>)_itemsControl.Items[sel];
            SetNextSlide(a.Key);
        }

        public void UpdateLyrics()
        {
            Lyrics.Clear();
            foreach (string s in Song.ScreenAll)
            {
                XmlDocument r = new XmlDocument();
                r.LoadXml(s);

                if (r.ChildNodes[0].LocalName == "LyricPanel")
                {
                    string id = r.ChildNodes[0].Attributes["c:Id"].Value;
                    foreach (XmlNode l in r.ChildNodes[0].ChildNodes)
                    {
                        if (l.Prefix == "")
                        {
                            UIElement control = (UIElement)XamlReader.Parse(l.OuterXml);
                            Lyrics.Add(id, control);
                        }
                        else
                        {
                            if (l.Prefix == "video")
                            {
                                TextBlock control = new TextBlock();
                                control.Text = "PLACEHOLDER";
                                Lyrics.Add(id, control);
                            }
                        }
                    }
                }
                if (r.ChildNodes[0].LocalName == "FlatDisplay")
                {
                    foreach (XmlNode l in r.ChildNodes[0].ChildNodes[0].ChildNodes)
                    {
                        if (l.LocalName == "ResourceDictionary")
                        {
                            ParserContext pc = new ParserContext();
                            pc.BaseUri = new Uri(_song.SongFileName.Remove(_song.SongFileName.LastIndexOf("/")));
                            ResourceDictionary a = (ResourceDictionary)XamlReader.Parse(l.OuterXml, pc);
                            this.Resources = a;
                        }
                        else
                        {
                            string id = l.Attributes["x:Key"].InnerText;
                            ParserContext pc = new ParserContext();
                            pc.BaseUri = new Uri(_song.SongFileName.Remove(_song.SongFileName.LastIndexOf("/")));
                            Brush a = (Brush)XamlReader.Parse(l.OuterXml, pc);
                            this.Resources.Add(id, a);
                        }
                    }
                    foreach (string j in this.Resources.Keys)
                    {
                        AddSlide(j);
                    }
                    foreach (ResourceDictionary d in this.Resources.MergedDictionaries)
                    {
                        foreach (string j in d.Keys)
                            AddSlide(j);
                    }
                }

            }
            if (AutoStart)
                StartSong();
        }


        private void AddSlide(string j)
        {
            if (j.StartsWith(LyricControlName))
            {
                TextBlock b = new TextBlock();
                b.Background = (Brush)this.Resources.FindName(j);
                b.Width = 160 * 2;
                b.Height = 90 * 2;
                Lyrics.Add(j, b);
            }
        }
    }
}
